/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.SRV;

import com.google.gson.Gson;
import controller.SRV.*;
import entity.MDoctor;
import entity.MHospital;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.SrvCureservice;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import javax.ejb.EJB;
import session.MDoctorFacade;
import session.MHospitalFacade;
import session.SrvCureserviceFacade;
import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;

@WebServlet(name = "SRV_SearchService",
loadOnStartup = 1,
urlPatterns = {"/SRV/SearchService",
    "/SRV/SearchService/grd_search",
    "/SRV/SearchService/dialog_detail"})
public class SRV_SearchService extends HttpServlet {

    private String sampleServletContext;
    @EJB
    SrvCureserviceFacade srvCureserviceFacade;
    @EJB
    MHospitalFacade mHospitalFacade;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        super.init(servletConfig);

        // initialize servlet with configuration information
        sampleServletContext = servletConfig.getServletContext().getInitParameter("sampleServletContext");
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        // if category page is requested
        if (userPath.equals("/Srv/SearchService")) {
            userPath = "/Srv/SearchService";
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as
        // 8-bit Unicode (e.g., for Czech characters)
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();


        if (userPath.equals("/SRV/SearchService/grd_search")) {
            response.setContentType("text/json;charset=utf-8");
            String qstr_page = request.getParameter("page"); // get the requested page
            String qstr_limit = request.getParameter("rows"); // get how many rows we want to have into the grid
            String qstr_sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
            String qstr_sord = request.getParameter("sord"); // get the direction

            if (qstr_sidx.isEmpty()) {
                qstr_sidx = "id";
                qstr_sord = "asc";
            }

            String txtName = (request.getParameter("txtName") != null) ? request.getParameter("txtName") : "";
            String txtPrice = (request.getParameter("txtPrice") != null) ? request.getParameter("txtPrice") : "";
            String txtCurrency = (request.getParameter("txtCurrency") != null) ? request.getParameter("txtCurrency") : "";
            String txtDoctorName = (request.getParameter("txtDoctorName") != null) ? request.getParameter("txtDoctorName") : "";
            String txtHospitalKeyword = (request.getParameter("txtHospitalKeyword") != null) ? request.getParameter("txtHospitalKeyword") : "";

            PrintWriter out = response.getWriter();
            List<SrvCureservice> lSrvCureservice;
            List rows;
            JQGridRow row;
            List cells;
            String strJson = "";
            int totalRecords = 0;
            int endList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page);
            int startList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page) - Integer.parseInt(qstr_limit);
            try {
                //Query Java Object
                lSrvCureservice = srvCureserviceFacade.LoadDataService(txtName, txtPrice, txtCurrency, txtDoctorName, txtHospitalKeyword, qstr_sidx, qstr_sord);
                totalRecords = lSrvCureservice.size();
                if (endList>totalRecords){
                    endList=totalRecords;
                }
                //Use List rows
                rows = new ArrayList();
                if (!lSrvCureservice.isEmpty()) {
                    for (SrvCureservice obj : lSrvCureservice.subList(startList, endList)) {
                        row = new JQGridRow();
                        row.setId(obj.getId());

                        cells = new ArrayList();
                        cells.add(obj.getId().toString());
                        cells.add(obj.getName());
                        cells.add(obj.getPrice().toString());
                        cells.add(obj.getCurrency());
                        if (obj.getMDoctor() != null) {
                            cells.add(obj.getMDoctor().getName() + " " + obj.getMDoctor().getSurname());
                        } else {
                            cells.add("");
                        }
                        if (obj.getMHospital() != null) {
                            cells.add(obj.getMHospital().getName());
                        } else {
                            cells.add("");
                        }


                        row.setCell(cells);
                        rows.add(row);
                    }
                }

                strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(qstr_page), Integer.parseInt(qstr_limit), totalRecords, rows);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lSrvCureservice = null;
                rows = null;
                row = null;
                cells = null;
                strJson = null;
            }

            isDispatcher = false;
        }

        if (userPath.equals("/SRV/SearchService/dialog_detail")) {
            response.setContentType("text/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            String cureServiceId = request.getParameter("id");
            List<SrvCureservice> lSrvCureservice;
            Map mapCureService = null;
            List listCureService = new LinkedList();

            String strJson = "";

            try {
                //Query Java Object
                Gson gson = new Gson();
                lSrvCureservice = srvCureserviceFacade.findByServiceId(cureServiceId);
                if (!lSrvCureservice.isEmpty()) {
                    for (SrvCureservice obj : lSrvCureservice) {
                        mapCureService = new LinkedHashMap();
                        mapCureService.put("id", obj.getId());
                        mapCureService.put("name", obj.getName());
                        mapCureService.put("price", obj.getPrice());
                        mapCureService.put("Currency", obj.getCurrency());
                    if (obj.getMDoctor() != null) {
                        mapCureService.put("Doctor_id", obj.getMDoctor().getId());
                        mapCureService.put("Doctor_name", obj.getMDoctor().getName());
                        mapCureService.put("Doctor_surname", obj.getMDoctor().getSurname());
                        if (obj.getMDoctor().getSex()){
                            mapCureService.put("Doctor_sex", "Male");
                        }else{
                            mapCureService.put("Doctor_sex", "Female");
                        }
                        mapCureService.put("Doctor_code", obj.getMDoctor().getCode());
                    }

                    if (obj.getMHospital() != null) {
                        mapCureService.put("Hospital_id", obj.getMHospital().getId());
                        mapCureService.put("Hospital_name", obj.getMHospital().getName());
                        mapCureService.put("Hospital_location", obj.getMHospital().getLocation());
                        mapCureService.put("Hospital_hospitalLevel", obj.getMHospital().getHospitalLevel());
                        mapCureService.put("Hospital_latitude", obj.getMHospital().getLatitude());
                        mapCureService.put("Hospital_longtitude", obj.getMHospital().getLongtitude());
                    }
                        listCureService.add(mapCureService);
                    }
                }

                //@TODO : Add Json Value
                strJson = gson.toJson(listCureService);//JSONValue.toJSONString(listDoctor);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                listCureService = null;
                strJson = null;
            }
            isDispatcher = false;
        }
        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

    }
}
